//
//  SYCustomRefreshControl.swift
//  YANAWeibo
//
//  Created by mac on 16/5/23.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

enum CustomRefreshState: Int {
    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
}

class SYCustomRefreshControl: UIControl {
    
    var refreshState: CustomRefreshState = .Normal {
        didSet {
            switch refreshState {
            case .Normal:
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.currentScrollView?.contentInset.top -= 50
                    })
                }
                print("normal")
            case .Pulling:
                print("pulling")
            case .Refreshing:
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top += 50
                })
                print("refreshing")
                // 告诉使用者要刷新数据
                sendActionsForControlEvents(.ValueChanged)
            }
        }
    }
    
    var currentScrollView: UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = UIColor.orangeColor()
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        print("------------")
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        
        currentScrollView = scrollView
        
        // 设置frame
        height = 50
        width = currentScrollView!.width
        y = -50
    }
    
    // kvo 监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if currentScrollView!.dragging {
            // 拖动情况下只有两种情况
            let maxY = -(currentScrollView!.contentInset.top + 50)
            let contentOffSetY = currentScrollView?.contentOffset.y
            if contentOffSetY < maxY && refreshState == .Normal {
                refreshState = .Pulling
            }
        } else {
            // 松手
            if refreshState == .Pulling {
                refreshState = .Refreshing
            }
        }
    }
    
    func endRefreshing() {
        refreshState = .Normal
    }
    
    deinit {
        // 移除kvo
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
